<template>
	<uni-popup ref="popup" @change="change" type="bottom">
		<view class="popup-box">
			<view class="head">
				<image @click="showImg(`${baseUrl}${goodsInfo.image}`)" class="goods-img"
					:src="`${baseUrl}${goodsInfo.image}`" mode="aspectFill" />
				<view class="head-text">
					<!-- 不带图片 -->
					<template v-if="false">
						<text class="price" v-if="!selectGood.price">0</text>
						<text class="price" v-else>{{ Number(selectGood.price).toFixed(2) }}</text>
						<text class="spec">{{ selectGood.id ? selectGood.difference.join("、") : "库存不足" }}</text>
					</template>

					<text class="price">{{ sku.length ? sku[specIndex].price : 0 }}</text>
					<text class="spec">{{ sku.length ? sku[specIndex].difference.join("、") : "库存不足" }}</text>
				</view>
			</view>
			<view class="spec-box">
				<!-- 带图片的规格 -->
				<template>
					<view class="title" style="margin-top: 0">规格选择</view>
					<view class="spec-list">
						<view @click="chooseSpec(item, i)" class="spec-item" :class="{ selected: i == specIndex }"
							v-for="(item, i) in sku" :key="i">
							<image class="spec-img" :src="`${baseUrl}${item.thumbnail}`" mode="aspectFill"></image>
							<view class="spec-text">{{ item.difference.join("、") }}</view>
						</view>
					</view>
				</template>
				<!-- 不带图片的规格 -->
				<template v-if="false">
					<view v-for="(item, index) in spu" :key="index">
						<view class="title">{{ item.name }}</view>
						<!-- 普通规格 -->
						<view class="spec-list-mini">
							<view class="spec-item" :class="{ selected: spec.selected }" v-for="(spec, i) in item.item"
								:key="i" @click="chooseSpec(item, spec, i)">
								<view class="spec-text">{{ spec.name }}</view>
							</view>
						</view>
					</view>
				</template>
			</view>
			<view class="title" style="margin-top: 46rpx">
				<text>数量</text>
				<!-- <text class="hint">(限购10件)</text> -->
				<text class="hint">(库存{{ sku.length ? sku[specIndex].stock : 0 }}件)</text>
				<view style="flex: 1"></view>
				<view class="num-box"><text class="minus" @click="reduce">-</text><text
						class="num">{{ number }}</text><text class="add" @click="add">+</text></view>
			</view>
			<view class="btns">
				<view class="btn" v-if="specType == 'addCar'" :class="{ 'btn-yellow': specType == 'addCar' }"
					@click="addToCart()">加入购物车</view>
				<view class="btn" v-if="specType == 'pay'" :class="{ 'btn-yellow': specType == 'pay' }"
					@click="buyNow()">立即购买</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		BASE_URL
	} from "@/utils/env.js";
	export default {
		name: "selectSpec",
		props: {
			goodsInfo: {
				type: Object,
				default: {},
			},
			specType: {
				type: String,
				default: "addCar", //addCar加入购物车,pay立即购买
			},
		},
		data() {
			return {
				baseUrl: BASE_URL,
				sku: [],
				spu: [],
				number: 1,
				// 选中的规格下标
				specIndex: 0,
			};
		},
		computed: {
			// 根据spu选中的规格去匹配sku里的数据，返回匹配到的sku数据
			selectGood() {
				if (this.sku.length == 0) {
					return [];
				}
				let selectedSpec = this.spu.reduce((pre, cur) => {
					let selectSpec = cur.item.find((spec) => spec.selected);
					if (selectSpec) {
						pre.push(selectSpec.name);
					} else if (cur.item.length == 1) {
						pre.push(cur.item[0].name);
					} else {
						return [];
					}
					return pre;
				}, []);
				let matchedSku = this.sku.find((sku) => {
					return sku.difference.every((spec, index) => spec == selectedSpec[index]);
				});
				if (matchedSku) {
					matchedSku.number = this.number;
				}
				return matchedSku ? matchedSku : [];
			},
		},
		methods: {
			change(e){
				this.$emit('change',e)
			},
			// 规格选择
			chooseSpec(item, spec) {
				item.item.forEach((item) => {
					item.selected = false;
				});
				spec.selected = true;
				if (this.spu.every((item) => item.item.some((spec) => spec.selected))) {
					if (this.selectGood.length == 0) {
						uni.showToast({
							title: "库存不足",
							icon: "none",
						});
					}
				}
			},
			// 减少数量
			reduce() {
				if (this.number > 1) {
					this.number--;
				}
			},
			// 增加数量
			add() {
				// this.number++;
				if (this.number < this.sku[this.specIndex].stock) {
					this.number++;
				}
			},
			// 加入购物车
			async addToCart() {
				try {
					await this.compareArrays();
					let data = this.sku[this.specIndex];
					data.number = this.number;
					// this.$emit("addToCart", this.selectGood);
					this.$emit("addToCart", data);
				} catch (error) {
					return uni.showToast({
						title: error,
						icon: "none",
					});
				}
			},
			// 立即购买
			async buyNow() {
				try {
					await this.compareArrays();
					let data = this.sku[this.specIndex];
					data.number = this.number;
					// this.$emit("buyNow", this.selectGood);
					this.$emit("buyNow", data);
				} catch (error) {
					return uni.showToast({
						title: error,
						icon: "none",
					});
				}
			},
			// 判断是否可以加入购物车或者立即购买
			compareArrays() {
				return new Promise((resolve, reject) => {
					// if (!this.spu.every((item) => item.item.some((spec) => spec.selected))) {
					//   reject("请选择规格");
					// }
					// if (this.spu.every((item) => item.item.some((spec) => spec.selected))) {
					//   if (this.selectGood.length == 0) {
					//     reject("库存不足");
					//   }
					// }
					// resolve();

					if (!this.sku.length) {
						reject("库存不足");
					}
					if (this.sku[this.specIndex].stock == 0) {
						reject("库存不足");
					}

					resolve();
				});
			},
			close() {
				console.log(1);
				
				this.$refs.popup.close();
			},
			showImg(url) {
				uni.previewImage({
					urls: [url],
				});
			},

			/* 多规格 */
			// 多规格选择
			chooseSpec(item, specIndex) {
				this.specIndex = specIndex;
			},
		},
		watch: {
			goodsInfo: {
				handler(newVal) {
					this.sku = newVal.sku;
					this.spu = newVal.spu.map((item) => {
						return {
							...item,
							item: item.item.map((spec, specIndex) => {
								return {
									...spec,
									selected: specIndex === 0,
								};
							}),
						};
					});
				},
				deep: true,
			},
		},

		// 组件周期函数--监听组件挂载完毕
		mounted() {},
		// 组件周期函数--监听组件数据更新之前
		beforeUpdate() {},
		// 组件周期函数--监听组件数据更新之后
		updated() {},
		// 组件周期函数--监听组件激活(显示)
		activated() {},
		// 组件周期函数--监听组件停用(隐藏)
		deactivated() {},
		// 组件周期函数--监听组件销毁之前
		beforeDestroy() {},
	};
</script>

<style lang="scss" scoped>
	::v-deep.uni-popup {
		z-index: 9999999999999999999 !important;
	}

	.popup-box {
		width: 100%;
		padding: 42rpx 22rpx;
		box-sizing: border-box;
		background-color: #fff;
		max-height: 1200rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		border-radius: 20rpx 20rpx 0 0;
	}

	.head {
		display: flex;
		align-items: center;

		.goods-img {
			width: 160rpx;
			height: 160rpx;
			border-radius: 10rpx;
		}

		.head-text {
			display: flex;
			flex-direction: column;
			margin-left: 20rpx;

			.price {
				font-size: 48rpx;
				color: #e72a2a;
				font-weight: 600;
			}

			.price::before {
				content: "¥";
				font-size: 24rpx;
				font-weight: normal;
			}

			// .price::after {
			//   content: "起";
			//   font-size: 24rpx;
			// }
			.spec {
				font-size: 30rpx;
				color: #333333;
				margin-top: 38rpx;
			}
		}
	}

	.spec-box {
		flex: 1;
		overflow-y: auto;
		margin-top: 24rpx;
	}

	.title {
		font-size: 34rpx;
		font-weight: 600;
		margin-top: 20rpx;
		display: flex;
		align-items: center;

		.hint {
			font-size: 28rpx;
			color: #999999;
			margin-left: 10rpx;
			font-weight: normal;
			flex: 1;
		}

		.num-box {
			display: flex;
			align-items: center;
		}

		.minus,
		.add {
			display: inline-flex;
			width: 44rpx;
			height: 44rpx;
			background-image: linear-gradient(to bottom, #ffa233, #fb4c4c);
			justify-content: center;
			align-items: center;
			color: #fff;
			border-radius: 50%;
		}

		.num {
			font-size: 38rpx;
			color: #666666;
			margin: 0 22rpx;
			font-weight: normal;
		}
	}

	.spec-list {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 16rpx 18rpx;
		margin-top: 20rpx;

		.spec-item {
			height: 336rpx;
			background-color: #f8f8f8;
			display: flex;
			flex-direction: column;
			border-radius: 16rpx;
			overflow: hidden;
			border: 1px solid transparent;

			.spec-img {
				width: 100%;
				height: 224rpx;
			}

			.spec-text {
				margin: 12rpx;
				flex: 1;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				font-size: 32rpx;
				color: #333333;
				font-weight: 600;
			}
		}
	}

	.spec-list-mini {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
		gap: 20rpx;

		.spec-item {
			padding: 14rpx 24rpx;
			background: #f8f8f8;
			border-radius: 16rpx;
			border: 1px solid transparent;

			.spec-text {
				font-size: 32rpx;
				color: #333;
				font-weight: 600;
			}
		}
	}

	// 选中状态
	.selected {
		// background: #e72a2a !important;
		border: 1px solid #e72a2a !important;

		.spec-text {
			color: #e72a2a !important;
		}
	}

	.btns {
		display: flex;
		align-items: center;
		margin-top: 40rpx;

		.btn {
			flex: 1;
			height: 96rpx;
			line-height: 96rpx;
			text-align: center;
			background: #f8f8f8;
			border-radius: 80rpx;
			font-size: 36rpx;
			color: #999999;
			font-weight: 600;
		}

		.btn-yellow {
			background: linear-gradient(135deg, #ffa233 0%, #fb4c4c 100%);
			color: #fff;
		}

		.btn+.btn {
			margin-left: 106rpx;
		}
	}
</style>